package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.commonutils.RandomUtil;
import com.commonutils.results;
import com.entity.pojo.Concept;
import com.entity.pojo.Resources;
import com.entity.vo.ConceptVo;
import com.service.ConceptService;
import com.service.ResourcesService;
import com.utils.InitData;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenmo
 * @since 2022-04-02
 */
@CrossOrigin
@RestController
@RequestMapping("/concept")
public class ConceptController {
    @Resource
    private ConceptService conceptService;

    @Resource
    private InitData initData;

    @Resource
    private ResourcesService resourcesService;

    @ApiOperation("查询所有的知识点名称和id")
    @GetMapping("/getConceptsIdAndName")
    public results getCategoriesIdAndName() {
        List<Concept> allConceptsIdAndNameList = conceptService.list(new QueryWrapper<Concept>()
                .select("conceptId", "conceptName","conceptCode"));
        return results.ok().data("allConceptsIdAndNameList", allConceptsIdAndNameList);
    }

    @ApiOperation("根据知识点id查询知识点信息")
    @GetMapping("/getConceptById/{conceptId}")
    public results getConceptById(@PathVariable Integer conceptId) {
        Concept conceptInfo = conceptService.getById(conceptId);
        return results.ok().data("conceptInfo",conceptInfo);
    }

    @ApiOperation("多表组合条件查询知识点信息")
    @PostMapping("/getConceptsPageCondition/{current}/{limit}")
    public results getConceptsPageCondition(@PathVariable long current,
                                            @PathVariable long limit,
                                            @RequestBody(required = false) ConceptVo conceptQuery) {
//        if (conceptQuery.getIsDeleted().)
        conceptQuery.setIsDeleted(0);
        List<ConceptVo> conceptsList = conceptService.getConceptsPageCondition(current, limit, conceptQuery);
        int total = conceptsList.size();
        return results.ok().data("conceptsList", conceptsList).data("total", total);
    }

    @ApiOperation("增加新的目录")
    @PostMapping("addConcept")
    public results addConcept(@RequestBody Concept concept) {
        if (!StringUtils.hasText(concept.getCategoryName())) {
            return results.error("知识点名称不能为空");
        }
        initData.initConcept(concept);
        boolean saveFlag = conceptService.save(concept);
        System.out.println(concept);
        if (saveFlag) {
            return results.ok();
        } else {
            return results.error("未知错误，添加新的知识点失败");
        }
    }

    private void initInfo(Concept concept) {
        // 设置排序字段
        List<Concept> conceptList = conceptService.list(new QueryWrapper<Concept>().eq("categoryId", concept.getCategoryId()).select("positionId"));
        int maxPositionId = conceptList.stream().mapToInt(Concept::getPositionId).summaryStatistics().getMax();
        concept.setPositionId(maxPositionId + 1);
        // 设置唯一性代码（在记录数多了之后可能出现重复）
        Integer maxPrimaryId = conceptService.getOne(new QueryWrapper<Concept>().select("max(conceptId)")).getConceptId();
        String code = "C" + RandomUtil.getSixBitRandom() + maxPrimaryId;
        concept.setConceptCode(code);
    }

    @ApiOperation("修改课程信息")
    @PutMapping("updateConcept")
    public results updateConcept(@RequestBody Concept concept) {
        boolean updateFlag = conceptService.updateById(concept);
        if (updateFlag) {
            return results.ok();
        } else {
            return results.error("修改知识点信息失败");
        }
    }

    @ApiOperation("删除知识点")
    @DeleteMapping("deleteConcept/{conceptId}")
    public results deleteConcept(@PathVariable Integer conceptId) {
        int count = resourcesService.count(new QueryWrapper<Resources>().eq("conceptId", conceptId));
        if (count != 0) {
            return results.error("请先删除该知识点下的资源，再删除该知识点！");
        }
        boolean removeFlag = conceptService.removeById(conceptId);
        if (removeFlag) {
            return results.ok();
        } else {
            return results.error("删除知识点失败");
        }
    }

}

